package com.example.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.User;
import com.example.entity.vo.ResponseData;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author CDHong.it
 * @since 2023-06-27
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("login")
    @ResponseBody
    public ResponseData login(HttpSession session, @RequestBody User user) {
        User userEntity = userService.lambdaQuery()
                .eq(User::getUserNum, user.getUserNum())
                .eq(User::getUserPwd, user.getUserPwd())
                .eq(User::getRoleId, user.getRoleId())
                .one();
        // 逻辑判断
        if (Objects.nonNull(userEntity)) {
            session.setAttribute("roleId", userEntity.getRoleId());
            session.setAttribute("userName", userEntity.getUserName());
            return ResponseData.ok("登录成功！");
        }
        return ResponseData.fail("用户名或密码输入有误，请重新输入！");
    }

    @GetMapping("loginout")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }

    @GetMapping("list")
    @ResponseBody
    public ResponseData list(User user, Integer page, Integer limit) {
        Page<User> userPage = userService.lambdaQuery()
                .like(StringUtils.isNotEmpty(user.getUserNum()), User::getUserNum, user.getUserNum()).or()
                .like(StringUtils.isNotEmpty(user.getUserName()), User::getUserName, user.getUserName()).or()
                .like(user.getRoleId() != null, User::getRoleId, user.getRoleId())
                .page(new Page<>(page, limit));
        List<User> records = userPage.getRecords();
        long total = userPage.getSize();
        return ResponseData.page(total, records);
    }
}
